<script setup lang="ts">
import { ElLoading, ElMessage } from 'element-plus'
import LayoutTitle from '@/components/LayoutTitle/index.vue'
import ContentTitle from '@/components/ContentTitle/index.vue'
import Content from '@/components/Content/index.vue'
import { useAuth } from '@/stores/index'
import APICommon from '@/api/common'
import APIEnterPersonal from '@/api/enter-personal'
import type { SetShopAuthForm } from '@/api/enter-personal/types'
import { downloadFile } from '@/utils/index'

const $router = useRouter()

const { info } = storeToRefs(useAuth())
const { getInfo } = useAuth()


const formData = ref<any>({
    type: 'personal'
})

const refFrontSide = shallowRef<HTMLInputElement>()
const refBackSide = shallowRef<HTMLInputElement>()
const refCopyright = shallowRef<HTMLInputElement>()

function handleUploadFrontSide() {
    refFrontSide.value?.click()
}

function handleUploadBackSide() {
    refBackSide.value?.click()
}

function handleUploadCopyright() {
    refCopyright.value?.click()
}

function onUploadFrontSideChange(e: Event) {
    const dom = (e.target as HTMLInputElement)
    if (!dom.files) return
    if (!['image/png', 'image/webp', 'image/jpeg', 'image/gif', 'image/bmp', 'image/svg+xml', 'image/x-icon'].includes(dom.files[0].type)) {
        dom.value = ''
        ElMessage.error('只能上传图片文件，请重新选择文件。')
        return
    }
    const fileSize = dom.files[0].size
    const fileSizeMB = fileSize / (1024 * 1024)
    if (fileSizeMB > 5) return ElMessage.error('上传文件大小不能超过5MB，请重新选择文件。')
    const loading = ElLoading.service({ lock: true })
    const form = new FormData()
    form.append('file', dom.files[0])
    APIEnterPersonal.personalOcr(form).then(({ data }) => {
        formData.value.front_side = data.file
        formData.value.real_name = data.ocr.name
        formData.value.id_card = data.ocr.idno
        ElMessage.success('上传成功')
    }).finally(() => {
        /** 清除value，否者用户选择同一张图片，不会触发上传 */
        dom.value = ''
        loading.close()
    })
}

function onUploadBackSideChange(e: Event) {
    const dom = (e.target as HTMLInputElement)
    if (!dom.files) return
    if (!['image/png', 'image/webp', 'image/jpeg', 'image/gif', 'image/bmp', 'image/svg+xml', 'image/x-icon'].includes(dom.files[0].type)) {
        dom.value = ''
        ElMessage.error('只能上传图片文件，请重新选择文件。')
        return
    }
    const fileSize = dom.files[0].size
    const fileSizeMB = fileSize / (1024 * 1024)
    if (fileSizeMB > 5) return ElMessage.error('上传文件大小不能超过5MB，请重新选择文件。')
    const loading = ElLoading.service({ lock: true })
    const form = new FormData()
    form.append('file', dom.files[0])
    APIEnterPersonal.personalOcr(form).then(({ data }) => {
        formData.value.back_side = data.file
        formData.value.validthru = data.ocr.validthru
        ElMessage.success('上传成功')
    }).finally(() => {
        /** 清除value，否者用户选择同一张图片，不会触发上传 */
        dom.value = ''
        loading.close()
    })
}

function onUploadCopyrightChange(e: Event) {
    const dom = (e.target as HTMLInputElement)
    if (!dom.files) return
    if (!['image/png', 'image/jpeg', 'image/jpg'].includes(dom.files[0].type)) {
        dom.value = ''
        ElMessage.error('只能jpg、jpeg、png文件，请重新选择文件。')
        return
    }
    const fileSize = dom.files[0].size
    const fileSizeMB = fileSize / (1024 * 1024)
    if (fileSizeMB > 5) return ElMessage.error('上传文件大小不能超过5MB，请重新选择文件。')
    const loading = ElLoading.service({ lock: true })
    const form = new FormData()
    form.append('file', dom.files[0])
    APICommon.uploadFile(form).then(({ data }) => {
        formData.value.copyright = data.file
        ElMessage.success('上传成功')
    }).finally(() => {
        /** 清除value，否者用户选择同一张图片，不会触发上传 */
        dom.value = ''
        loading.close()
    })
}

const consent1 = shallowRef()
const consent2 = shallowRef()
const formRef = shallowRef()

function submitFormData() {
    if (!formData.value.front_side) return ElMessage.error('请上传身份证人物面')
    if (!formData.value.back_side) return ElMessage.error('请上传身份证国徽面')
    if (!formData.value.real_name) return ElMessage.error('请输入姓名')
    if (!formData.value.id_card) return ElMessage.error('请输入身份证号码')
    if (!formData.value.copyright) return ElMessage.error('请上传作品版权声明')
    if (!consent1.value) return ElMessage.error('请勾选同意《心安元素信息认证协议》')
    if (!consent2.value) return ElMessage.error('请勾选同意《心安元素店主合作协议》')
    const loading = ElLoading.service({ lock: true })
    APIEnterPersonal.setShopAuth(formData.value).then(({ msg }) => {
        ElMessage.success(msg)
        getInfo()
        $router.replace({
            name: 'Store'
        })
    }).finally(() => {
        loading.close()
    })
}

function getAuthInfo() {
    APIEnterPersonal.getAuthInfo('personal').then(({ data }) => {
        formData.value.real_name = data.real_name
        formData.value.id_card = data.id_card
        formData.value.back_side = data.back_side
        formData.value.front_side = data.front_side
    })
}

watch(() => info.value.user_type, (newValue) => {
    if (newValue == 'personal') {
        getAuthInfo()
    }
}, { immediate: true })

function handleJumpAgreement(type: string, mark: string) {
    window.open(`${import.meta.env.VITE_APP_WEB_URL}/agreement?type=${type}&mark=${mark}`, '_blank')
}

function handleDownload() {
    downloadFile('https://basis.xinanyuansu.cn/shop/shop_auth_personal.pdf', '作品版权声明.pdf')
}

</script>

<template>
    <div class="authentication">
        <el-form :model="formData" ref="formRef">
            <LayoutTitle class="nav" title="个人认证中心" />
            <Content class="center">
                <ContentTitle title="账号基本信息：" />
                <div class="info">
                    <div class="con">
                        <div class="label">用户名：</div>
                        <div class="value">{{ info.username }}</div>
                    </div>
                    <div class="con">
                        <div class="label">账号ID：</div>
                        <div class="value">{{ info.Invite_code }}</div>
                    </div>
                </div>
            </Content>
            <Content class="center">
                <ContentTitle title="上传身份信息：" />
                <div class="upload-info">
                    <div class="left">
                        <div @click="handleUploadFrontSide" class="front">
                            <img v-if="formData.front_side" :src="formData.front_side" alt="正面身份证照片">
                            <div v-else class="upload-text">
                                <div>+</div>
                                <div>身份证人物面</div>
                            </div>
                        </div>
                        <input ref="refFrontSide" type="file" @change="onUploadFrontSideChange" style="display: none;"
                            accept="image/*">
                        <div @click="handleUploadBackSide" class="back">
                            <img v-if="formData.back_side" :src="formData.back_side" alt="反面身份证照片">
                            <div v-else class="upload-text">
                                <div>+</div>
                                <div>身份证国徽面</div>
                            </div>
                        </div>
                        <input ref="refBackSide" type="file" @change="onUploadBackSideChange" style="display: none;"
                            accept="image/*">
                    </div>
                    <div class="right">
                        <el-form-item :label="`姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名：`">
                            <el-input v-model="formData.real_name" placeholder="读取上传的信息，无需填写" />
                        </el-form-item>
                        <el-form-item label="身份证号码：">
                            <el-input v-model="formData.id_card" placeholder="读取上传的信息，无需填写" />
                        </el-form-item>
                    </div>
                </div>
            </Content>
            <Content class="center">
                <ContentTitle title="售卖署名：" />
                <div class="signature-sale">
                    <div class="con">
                        <div class="label">作品售卖版权署名</div>
                        <div class="is-upload-copyright" v-if="formData.copyright">已上传</div>
                        <button type="button" class="value" v-if="formData.copyright"
                            @click="formData.copyright = undefined">重新上传</button>
                        <button type="button" class="value" @click="handleUploadCopyright" v-else>上传作品版权声明</button>
                        <input type="file" ref="refCopyright" style="display: none;" @change="onUploadCopyrightChange"
                            accept="image/*">
                    </div>
                    <div class="explain">
                        <p>《作品版权声明》<span @click="handleDownload">点击下载</span></p>
                        <p>说明：需要把文件打印签字/盖章的图片进行上传（大小为5MB内的JPG、JPEG、PNG图片）；</p>
                    </div>
                </div>
            </Content>
            <div class="bottom">
                <div>
                    <el-checkbox v-model="consent1" size="large">
                        同意
                    </el-checkbox>
                    <span class="agreement" @click="handleJumpAgreement('register', 'auth')">《心安元素信息认证协议》</span>
                </div>
                <div>
                    <el-checkbox v-model="consent2" size="large">
                        确认信息无误（不可改），并同意签署
                    </el-checkbox>
                    <span class="agreement" @click="handleJumpAgreement('shop', 'cooperate')">《心安元素店主合作协议》</span>
                </div>
                <button type="button" @click="submitFormData">提交店铺入驻信息</button>
            </div>

        </el-form>
    </div>
</template>

<style lang="scss">
.authentication {
    .bottom {
        width: 75%;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 20px 0;
        margin-bottom: 50px;

        button {
            width: 230px;
            height: 40px;
            border-radius: 5px;
            background-color: rgba(15, 64, 245, 1);
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            border: none;
            cursor: pointer;
        }

        div {
            display: flex;
            align-items: center;

            .agreement {
                cursor: pointer;
                line-height: 1em;
                color: #1684FC;
                font-size: 14px;
            }
        }
    }

    .center {
        width: 75%;
        margin: 0 auto;
        margin-bottom: 30px;

        .signature-sale {
            padding: 20px;

            .explain {
                display: flex;
                gap: 0 15px;
                margin-top: 15px;

                p {
                    font-size: 14px;

                    span {
                        cursor: pointer;
                    }

                    &:last-child {
                        color: rgba(154, 154, 154, 1);
                    }

                    &:first-child {
                        color: rgba(107, 173, 247, 1);
                    }
                }
            }

            .con {
                display: flex;
                align-items: center;
                gap: 0 35px;

                .is-upload-copyright {
                    color: #67C23A;
                }

                .value {
                    width: 190px;
                    height: 35px;
                    border-radius: 5px;
                    background-color: rgba(255, 255, 255, 1);
                    color: #1684FC;
                    font-size: 14px;
                    border: 1px dashed rgba(22, 132, 252, 1);
                    cursor: pointer;
                }

                .label {
                    color: rgba(16, 16, 16, 1);
                    font-size: 14px;
                }
            }
        }

        .upload-info {
            display: flex;
            justify-content: space-between;
            padding: 30px 45px;

            .right {
                width: 500px;

                .QR-code {
                    display: flex;
                    flex-direction: column;
                    align-items: flex-end;
                    margin-top: 32px;
                    margin-bottom: 56px;

                    div {
                        width: 115px;
                        height: 115px;
                        background-color: #eeeeee;
                    }

                    p {
                        color: rgba(16, 16, 16, 1);
                        font-size: 14px;
                        margin-top: 15px;
                    }
                }
            }

            .left {

                .front {
                    background-image: url('./images/front-side.png');
                    background-size: 100% 100%;
                }

                .back {
                    background-image: url('./images/back-side.png');
                    background-size: 100% 100%;
                }

                .front,
                .back {
                    width: 220px;
                    height: 140px;
                    margin-top: 20px;
                    cursor: pointer;

                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }
                }

            }
        }

        .info {
            display: flex;
            margin: 30px 0;
            padding: 0 50px;

            .con {
                display: flex;
                align-items: center;
                flex: 1;

                .value {
                    color: rgba(154, 154, 154, 1);
                    font-size: 14px;
                }

                .label {
                    color: rgba(16, 16, 16, 1);
                    font-size: 15px;
                }
            }
        }
    }

    .nav {
        margin-bottom: 20px;
    }
}
</style>
